﻿define([
  'models/abmManagers/userManager',
  'models/abmManagers/rolManager',
  'models/abmManagers/groupManager',
  'text!templates/abmManagers/abmBaseTmp.html',
  'text!templates/abmManagers/abmFormTmp.html',
  'text!templates/abmManagers/user/common/userCreate.html',
], function (UserModel, RolModel, GroupModel, BaseTmp, FormTmp, UniqTmp) {
    var view = Backbone.View.extend({
        el: $("#main"),
        _uId: "",
        render: function () {
            $("#mainLoading").show();
            $("div[data-rel='abm-user']").remove();
            var _this = this;
            this._uId = $.uuid();
            
            var baseTemplate = Handlebars.compile(BaseTmp);
            var formTemplate = Handlebars.compile(FormTmp);
            var uniqTemplate = Handlebars.compile(UniqTmp);

            var dataBaseTemplate = {
                id: _this._uId,
                dataRel: "abm-user", // cuidado, ref en js
                tmpClass: "user-create", // cuidado, ref en css
                title: translate("_newUser")
            };

            var html = baseTemplate(dataBaseTemplate);
            var html2 = formTemplate();
            var html3 = uniqTemplate();
            
            _this.$el.append(html);
            $("div[data-id='" + _this._uId + "']").find("div.abm-content").append(html2);
            $("div[data-id='" + _this._uId + "']").find("div.form-content").append(html3);

            postRender(_this.$el.find("div[data-id='" + _this._uId + "']"));
            _this.rolNGroup();

            _this.addHandlers();
            $("#mainLoading").hide();
        },
        rolNGroup: function () {
            var cmpyId = __currentSession.companyId;
            var rolMod = new RolModel(), groupMod = new GroupModel();

            var _rolItem = $("div[data-id='" + this._uId + "']").find("div.user-rol a");
            var _groupItem = $("div[data-id='" + this._uId + "']").find("div.user-group a");

            rolMod.List(cmpyId, function (dataRol) {
                groupMod.List(cmpyId, function (dataGroup) {
                    if (dataRol.length > 0) {
                        var rolList = [{ value: "", text: "" }];

                        for (var ii = 0; ii < dataRol.length; ii++) {
                            rolList[ii] = {
                                value: dataRol[ii].rolId,
                                text: dataRol[ii].name
                            }
                        }
                        _rolItem.editable({
                            pk: 1,
                            source: rolList,
                            success: function (response, newValue) {
                                $(this).attr("data-value", newValue);
                            }
                        });
                    }
                    if (dataGroup.length > 0) {
                        var groupsList = [{ value: "", text: "" }];

                        for (var i = 0; i < dataGroup.length; i++) {
                            groupsList[i] = {
                                value: dataGroup[i].groupId,
                                text: dataGroup[i].name
                            }
                        };
                        _groupItem.editable({
                            pk: 1,
                            source: groupsList,
                            success: function (response, newValue) {
                                $(this).attr("data-value", newValue);
                            }
                        });
                    }
                });
            });
        },
        save: function () {
            var _uId = this._uId;
            var _cmpyId = __currentSession.companyId;

            var _userForm = $("div[data-id='" + _uId + "']").find("form");
            if (!$(_userForm).validate().errorList.length > 0) {
                var _name = $("div[data-id='" + _uId + "']").find("div.user-name input").val();
                var _login = $("div[data-id='" + _uId + "']").find("div.user-login input").val();
                var _password = $("div[data-id='" + _uId + "']").find("div.user-password input").val();
                var _email = $("div[data-id='" + _uId + "']").find("div.user-email input").val();
                var _state = '0' != $("div[data-id='" + _uId + "']").find("div.user-state input").val();
                var _rolId = $("div[data-id='" + _uId + "']").find("div.user-rol a").attr("data-value");

                var _groupItem = $("div[data-id='" + _uId + "']").find("div.user-group a");
                var assignedGroups = [];

                var auxRowGroups = $(_groupItem).attr("data-value");
                if (auxRowGroups != undefined) {
                    var splitGroups = auxRowGroups.split(",");

                    for (var h = 0; h < splitGroups.length; h++) {
                        assignedGroups[h] = {
                            groupId: splitGroups[h]
                        };
                    }
                }

                var user = {
                    fullName: _name, userLogin: _login, active: _state,
                    email: _email, password: _password,
                    userCompanies: compData = [{
                        companyId: _cmpyId,
                        rolId: _rolId,
                        groups: assignedGroups
                    }]
                };

                new UserModel().Create(user, function () {
                    require(['controllers/abmManagers/userManager'], function (Controller) {
                        (new Controller()).show();
                    });
                });
            }
        },
        changeState: function () {
            this.checked ? $(this).attr('value', 1) : $(this).attr('value', 0);
        },
        cancel: function () {
            require(['controllers/abmManagers/userManager'], function (Controller) {
                (new Controller()).show();
            });
        },
        addHandlers: function () {
            $("div[data-id='" + this._uId + "']").find("div.user-state input").on("click", this.changeState);
            $("div[data-id='" + this._uId + "']").find("form").on("submit", $.proxy(function () {
                this.save();
                return false;
            }, this));
            $("div[data-id='" + this._uId + "']").find("div.submit button.btn-cancel").on("click", $.proxy(function () {
                this.cancel();
                return false;
            }, this));
            $("div[data-id='" + this._uId + "']").find("div.abm-top-options a.btn-close").on("click", this.cancel);
        }
    });
    return view;
});